package com.skillworld.webapp.web.pages.rest.language;

import java.util.Collections;
import java.util.List;
import java.util.Locale;

import org.apache.tapestry5.annotations.ContentType;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;

import com.skillworld.webapp.model.languageservice.LanguageService;
import com.skillworld.webapp.web.util.ErrorMessages;
import com.skillworld.webapp.web.util.LocaleDisplayComparator;
import com.skillworld.webapp.web.util.UserSession;

@ContentType("text/xml")
public class ListSupportedLanguages
{   
    @SuppressWarnings("unused")
    @Property
    private String errorMessage = null;

    @Property
    private List<Locale> supportedLanguages;
    
    @SuppressWarnings("unused")
    @Property
    private Locale lang;   // loop iterator
    
    @SuppressWarnings("unused")
    @Property
    private Locale locale;
    
    @Inject
    private LanguageService languageService;

    @SessionState(create=false)
    private UserSession userSession;
    
    private boolean userSessionExists;

    @Inject
    private Request request;
   
    
    void onPassivate() 
    {
        return;
    }
    
    void onActivate()
    {
        if (!userSessionExists)
        {
            errorMessage = ErrorMessages.NOT_LOGGED_IN;
            return;
        }
    
        String langParam = request.getParameter("lang");
        
        if (langParam == null)
        {  
            errorMessage = ErrorMessages.INVALID_ARGUMENTS;
            return;
        }

        locale = new Locale(langParam);
        supportedLanguages = languageService.listSupportedLanguages();
        Collections.sort(supportedLanguages, new LocaleDisplayComparator(locale));
    }
}
